const express = require('express');
const { success, failure } = require('../../utils/responses');
const router = express.Router();
const { Course, Category, User, Chapter } = require('../../models');
const { findListPagination } = require('../../utils/pagination');
router.get('/', async (req, res) => {
  try {
    let { categoryId } = req.query;

    if (!categoryId) {
      throw BadRequest('分类ID必填');
    }
    const condition = {
      attributes: { exclude: ['CategoryId', 'UserId'] },
      where: { categoryId },
    };
    const data = await findListPagination(req.query, (pagination) =>
      Course.findAndCountAll({ ...pagination, ...condition })
    );

    success({ res, data });
  } catch (error) {
    failure({ res, error });
  }
});

router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const course = await Course.findByPk(id, {
      attributes: { exclude: ['CategoryId', 'UserId'] },

      include: [
        {
          model: Category,
          as: 'category',
          attributes: ['id', 'name'],
        },
        {
          model: User,
          as: 'user',
          attributes: ['id', 'username', 'nickname', 'avatar', 'company'],
        },
        {
          model: Chapter,
          as: 'chapter',
          attributes: ['id', 'title', 'rank', 'createdAt'],
          order: [
            ['rank', 'ASC'],
            ['id', 'DESC'],
          ],
        },
      ],
    });
    if (!course) {
      throw new NotFound(`ID: ${id}的课程未找到。`);
    }
    success({ res, data: course });
  } catch (error) {
    failure({ res, error });
  }
});

module.exports = router;
